package com.woniuxy.base.service;

import com.woniuxy.base.repository.BaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

public class BaseService<T, R extends BaseRepository<T>> {
    @Autowired
    private R baseRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    public MongoTemplate getMongoTemplate() {
        return this.mongoTemplate;
    }

    @Transactional(
            rollbackFor = {Exception.class},
            transactionManager = "mongoTransactionManager"
    )
    public void removeById(Serializable id) {
        this.baseRepository.deleteById(id);
    }

    @Transactional(
            rollbackFor = {Exception.class},
            transactionManager = "mongoTransactionManager"
    )
    public void removeByIds(Serializable[] ids) {
        Serializable[] var2 = ids;
        int var3 = ids.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            Serializable id = var2[var4];
            this.baseRepository.deleteById(id);
        }

    }

    public T findById(Serializable id) {
        return this.baseRepository.findById(id).orElse(null);
    }

    public List<T> find(T example) {
        return this.baseRepository.findAll(Example.of(example));
    }

    public List<T> findAll() {
        return this.baseRepository.findAll();
    }

    public Page<T> findPage(T example, Pageable pageable) {
        return this.baseRepository.findAll(Example.of(example), pageable);
    }

    @Transactional(
            rollbackFor = {Exception.class},
            transactionManager = "mongoTransactionManager"
    )
    public List<T> saveAll(List<T> entityList) {
        return this.baseRepository.saveAll(entityList);
    }

    @Transactional(
            rollbackFor = {Exception.class},
            transactionManager = "mongoTransactionManager"
    )
    public T save(T entity) {
        return this.baseRepository.save(entity);
    }

    protected R getBaseRepository() {
        return this.baseRepository;
    }
}
